package leetcode_数组.leetcode_数组的遍历;

import java.util.Arrays;

// 三个数的最大乘积
public class _628 {
    public static void main(String[] args) {
        System.out.println(maximumProduct(new int[]{1, 2, 3, 4}));
    }

    public static int maximumProduct1(int[] nums) {
        int length = nums.length;
        Arrays.sort(nums);
        return Math.max(nums[0] * nums[1] * nums[length - 1], nums[length - 1] * nums[length - 2] * nums[length - 3]);
    }

    public static int maximumProduct(int[] nums) {
        // min2 < min1 < max3 < max2 < max1
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < min2) {
                min1 = min2;
                min2 = nums[i];
            } else if (nums[i] < min1) {
                min1 = nums[i];
            }
            if (nums[i] > max1) {
                max3 = max2;
                max2 = max1;
                max1 = nums[i];
            } else if (nums[i] > max2) {
                max3 = max2;
                max2 = nums[i];
            } else if (nums[i] > max3) {
                max3 = nums[i];
            }
        }
        return Math.max(min1 * min2 * max1, max1 * max2 * max3);
    }

}
